#!/usr/bin/python
# -*- coding:utf-8 -*-
'''
百度翻译api
Created on 2015年3月18日

@author: weichengshuang
'''
import urllib2
import urllib

TIMEOUT = 10

def post(url, data):
    """
    #post request
    @param url: post url
    @param data: post data
    """
    req = urllib2.Request(url)
    data = urllib.urlencode(data)
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor)
    response = opener.open(req, data,timeout=TIMEOUT)
    return response.read()

def translate(query, From="en", To="zh", transtype="trans", simple_means_flag=3, transapi="http://fanyi.baidu.com/v2transapi"):
    """
    #百度翻译api python client
    @param query: 翻译内容
    """
    assert query
    data = {
            "from":From,
            "to":To,
            "transtype":transtype,
            "simple_means_flag":simple_means_flag,
            "query":query,
            }
    response = post(transapi, data)
    if response:
        start = response.find('"dst"')
        end = response.find('"src"')
        if start > -1 and  end > -1:
            return response[start + 7:end-2].decode('unicode_escape')
    return ""


def test():
    querys = ["好的工作文件转换太快。It uses about 1gb of my storage space please update I cannot use such a big app....", "Nice work file tranfer so fast."]
    for query in querys:
        print query, "===>", translate(query)
        print query, "===>", translate(query,From="zh",To="en")
    print "---------"
    
if __name__ == '__main__':
    test()
